﻿var washSearch = {};
$(function () {
    //选公客池时不会出现导入批次下拉框，只有潜客才有
    $("#PotentialSpan input").unbind("click");
    $("#PotentialSpan input").click(function () {
        //隐藏  城区片区下拉列
        $("#SystemCustomersDiv").hide();
        //选择的是否是  公司资源池 0 不是 1 是
        $("#IsSystemCustomer").val("0");
        if ($("#potentialCustRadio").attr("checked")) {//潜客
            $("#ImportNoDiv").css("display", "inline");
            $("#ajaxPages").css("display", "none");
            $("#ajaxPagesPreCust").css("display", "").html("<div id='loadimg' class='load-img2'><img src='/static/app/img/loading-big.gif' width='65' height='65' /></div>");
            $("#hiddenPageIndexPre").val("");//清空隐藏域值pageIndex(页面跳转会改变隐藏域值)
            $("#hiddenAutoCall").val("0");//点击时单选后不自动拨打电话
            $("#hidPotentialSeach").click();
        } else if ($("#publicCustRadio").attr("checked")) {//公客池
            $("#ImportNoDiv").css("display", "none");
            $("#ajaxPagesPreCust").css("display", "none");
            $("#ajaxPages").css("display", "").html("<div id='loadimg' class='load-img2'><img src='/static/app/img/loading-big.gif' width='65' height='65' /></div>");
            $("#hiddenPageIndexPub").val("");//清空隐藏域值pageIndex(页面跳转会改变隐藏域值)
            $("#hiddenAutoCall").val("0");//点击时单选后不自动拨打电话
            $("#hidWashSearch").click();
        } else {//公司资源池
            $("#SystemCustomersDiv").show();
            //选择的是否是  公司资源池 0 不是 1 是
            $("#IsSystemCustomer").val("1");
            $("#hidPotentialSeach").click();
            $("#ajaxPages").css("display", "none");
            $("#ImportNoDiv").css("display", "none");
            $("#ajaxPagesPreCust").show();
        }
        $("#SystemCustomersDiv").children().children("input").attr("readonly", "readonly")
    });

    var loadFlag = true;
    //导入洗客池 
    $("#btnSubmitImport").unbind("click");
    $("#btnSubmitImport").bind("click", function () {
        if (!$("#potentialCustRadio").attr("checked") && !$("#publicCustRadio").attr("checked") && !$("#SystemCustomers").attr("checked")) {
            $.OKDialogAgency('<div class="tc">请选择导入途径！</div>');
            return false;
        }

        //公司资源池
        if ($("#SystemCustomers").attr("checked")) {
            var districtName = $("#citySelect").combobox("getValue");
            var areaName = $("#areaSelect").combobox("getValue");
            if (districtName == "全部") {
                districtName = "";
            }
            if (areaName == "全部") {
                areaName = "";
            }
            $.AjaxAgency("/Customer/PreSystemCustomersList", {
                DistrictName: districtName,
                AreaName: areaName
            }, function (data) {
                $("#btnSubmitImport").attr("disabled", "disabled");
                if (data.Flag) {
                    $.OKDialogAgency('<div class="tc">导入成功(' + data.Result.length + ')条！</div>', '提示', function () {
                        $("#hidPotentialSeach").click();
                    });
                } else {
                    $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
                }
            });
        }

        if ($("#publicCustRadio").attr("checked")) {
            if ($("#hidPermissions").val().indexOf("Customer.PublicInquiryToMyself.Other") < 0) {
                $.OKDialogAgency('<div class="tc">无公客转私客权限，公客不能导入洗客池！</div>');
                return false;
            }
            var req = {};
            $.dialog({
                id: "publicAccountSelectorDiv",
                title: "公客池",
                init: function () {
                    loadFlag = true;
                    $('#publicAccountsSelector').combobox({
                        url: 'get-publicaccounts',
                        method: 'get',
                        valueField: 'id',
                        textField: 'text',
                        inputCode: 'inputCode',
                        filter: function (q, row) {
                            var opts = $(this).combobox('options');
                            return (row[opts.inputCode].indexOf(q) == 0 || row[opts.textField].indexOf(q) == 0);
                        },
                        onBeforeLoad: function () {
                            $('span.textbox.combo').addClass('outerSpan');
                            $('span.textbox.combo').css('width', '').css('height', '');
                            $('input.textbox-text.validatebox-text').css('width', '195px');
                            $('a[class="textbox-icon combo-arrow"]').css('height', '26px');
                        },
                        onLoadSuccess: function (data) {
                            if (loadFlag) {
                                loadFlag = false;
                                data.unshift({ "id": "", "text": "全部", "inputCode": "" });
                                $('#publicAccountsSelector').combobox("loadData", data);
                            }
                            return false;
                        }
                    });
                },
                lock: true,
                content: $("#spanPublicAccountCustomer").html(),
                ok: function () {
                    var arr = new Array();
                    var value = $(".textbox-value[name='PublicAccount']").val();
                    if (value) {
                        arr.push(value);
                    }
                    else {
                        var keys = $('#publicAccountsSelector').combobox("getData");
                        for (var i = 1; i < keys.length; i++) {
                            arr.push(keys[i].id);
                        }
                    }
                    req.strKeyIds = JSON.stringify(arr);
                    $.AjaxAgency('/Customer/import-washcustomer-ajax', req,
                        function (data) {
                            if (!data.Flag) {
                                $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
                            } else {
                                $.OKDialogAgency('<div class="tc">导入成功(' + data.Result + ')条！</div>', '提示', function () {
                                    $("#hidWashSearch").click();
                                });
                            }
                        }
                    );
                },
                cancelVal: '关闭',
                cancel: function () {
                    this.close();
                }
            });
        }
        if ($("#potentialCustRadio").attr("checked")) {
            var ImprotKeyIds = "";
            var datas = $("#ImportNo").combobox("getData");
            if (!$("#ImportNo").combobox("getValue")) {
                if (datas.length > 1 && datas[0].ImportNo == "全部") {
                    for (var i = 1; i < datas.length; i++) {
                        ImprotKeyIds += "," + datas[i].ImprotKeyId;
                    }
                }
            }
            else {
                ImprotKeyIds = $("#ImportNo").combobox("getValue");
            }
            var reqData = {
                "ImprotKeyIds": ImprotKeyIds
            };
            $.AjaxAgency("/Customer/import-washPrecustomer-ajax", reqData, function (data) {
                $("#btnSubmitImport").attr("disabled", "disabled");
                if (!data.Flag) {
                    $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
                } else {
                    $.OKDialogAgency('<div class="tc">导入成功(' + data.Result + ')条！</div>', '提示', function () {
                        $("#hidPotentialSeach").click();
                    });
                }
            });
        }


    });

    //浮动的工具栏 yjj添加
    var state1 = true; //存储顶部显示的状态
    var state2 = true; //存储顶部显示的状态
    $(window).scroll(function () {
        if ($(window).scrollTop() > $("#ajaxPages").offset().top) {
            if (state1) {
                //执行浮动层出现后的代码
                $("#editToolsBox").addClass("float-edit-toos");
                //表头排序
                $('.fixed-div div').find(".fixed-span").unbind("click");
                $('.fixed-div div').find(".fixed-span").click(function () {
                    var resultVal = $(this).attr('callValue');
                    if (resultVal) {
                        $('#hiddenSortValue').val(resultVal);
                        $('#searchForm').submit();
                    }
                });
                //解决全部客源、公客池文字列表，锁定表头出现时，排序样式丢失的问题
                var n = $("#gdIndexCustomerList th").size();
                for (var i = 0; i < n; i++) {
                    $(".fixed-div div").find(".fixed-span").eq(i).find("span").removeClass().addClass($("#gdIndexCustomerList th").eq(i).find("span").attr("class"));
                }

                $(".fixed-div").show();
                $("#gdIndexCustomerList .thead").css("visibility", "hidden");
                $("#thead .last").css("width", "100px");
            }
            state1 = false;
        } else {
            if (!state1) {
                //执行浮动层出现前的代码
                $("#editToolsBox").removeClass("float-edit-toos");
                $(".fixed-div").hide();
                $("#gdIndexCustomerList .thead").css("visibility", "visible");
                $("#thead .last").css("width", "100px");
            }
            state1 = true;
        }
        $(".tab-panel-wrapper").scroll(function () {
            var l = $(".tab-panel-wrapper").scrollLeft();
            $(".fixed-div div").css("margin-left", "-" + l + "px");
        });

        //潜客浮动工具栏问题
        if ($(window).scrollTop() > $("#ajaxPagesPreCust").offset().top) {
            if (state2) {
                //执行浮动层出现后的代码
                $("#editToolsBox").addClass("float-edit-toos");

                var n = $("#gdIndexPreCustomerList th").size();
                for (var i = 0; i < n; i++) {
                    $(".fixed-div.precust div").find(".fixed-span").eq(i).find("span").removeClass().addClass($("#gdIndexPreCustomerList th").eq(i).find("span").attr("class"));
                }
                $(".fixed-div.precust").show();
                $("#gdIndexPreCustomerList .thead").css("visibility", "hidden");
                $("#thead .last").css("width", "100px");
            }
            state2 = false;

        } else {
            if (!state2) {
                //执行浮动层出现前的代码
                $("#editToolsBox").removeClass("float-edit-toos");
                $(".fixed-div.precust").hide();
                $("#gdIndexPreCustomerList .thead").css("visibility", "visible");
                $("#thead .last").css("width", "100px");
            }
            state2 = true;
        }
    });

    //点击真获取真号码
    $(".numView").unbind("click");
    $(".numView").bind("click", function () {
        var preCustomerKeyId = $(this).attr("preCustomerKeyId");
        var reqData = {
            "PreCusKeyId": preCustomerKeyId
        };
        $.AjaxAgency('/customer/browse-mobile', reqData, function (data) {
            if (data.substring(0, 5) == "error") {
                $.OKDialogAgency('<center>' + data + '</center>');
            }
            else {
                $.dialog({
                    id: "phonesInfo",
                    title: "查看号码",
                    init: function () {
                    },
                    lock: true,
                    content: $("#phones").html(),
                });

                for (var i = 0; i < data.split(',').length; i++) {
                    $(".aui_dialog #InfoPhone").append('<tr><td><span class="iphone-info"><i class="iphone-icon"></i></span>' + data.split(',')[i] + '</td></tr>');
                }
            }
        });
    });
});


washSearch.beginSearch = function () {
};

washSearch.OnSuccess = function () {
}


//潜客洗客池中跟进图标按钮
$(".followPreCus").unbind('click');
$(".followPreCus").bind("click", function () {
    var obj = $(this)
    //防重复提交
    var opFlag = obj.parents(".op").attr("data-flag");
    if (obj.hasClass("setcolor") || opFlag != "true") {
        return;
    }
    obj.parents(".op").attr("data-flag", "false");
    var currentElement = $(this);
    var keyId = currentElement.attr('keyid');
    var customerKeyId = currentElement.attr('custkeyid');
    var trustorKeyId = currentElement.attr('trustorKeyId');
    $("#hiddenCustKeyId").val(customerKeyId);
    var reqData = {
        'importKeyId': keyId,
        'trustorKeyId': trustorKeyId,
        'IsPrePub': false
    };

    var followType = currentElement.attr("isturnprivate");
    if (followType != "5") {
        reqData.FollowType = followType;
        reqData.PreCustName = currentElement.parent().prevAll().eq(1).text();
        reqData.CustKeyId = customerKeyId;
        reqData.RequestSourceType = 2;
        reqData.CustomerName = obj.parents("tr").children(".custName").html();
        reqData.SourceObjectKeyId = customerKeyId;
        reqData.Mobile = obj.attr("mobile");
        reqData.Type = obj.text();
        //if (reqData.Mobile == "" || reqData.Mobile == undefined) {
        //    //如果手机号为空  获取表格中的手机号
        //    reqData.Mobile = obj.parents("tr").children(".phone").html();
        //    if (reqData.Mobile != "") {
        //        //如果表格中的手机号不为空  清除两端的空格
        //        reqData.Mobile = reqData.Mobile.trim();
        //    }
        //}
        
        $.AjaxAgency("/customer/precust-add-follow", reqData, function (data) {
            if (!data.Flag) {
                if (data.ErrorMsg != null || data.ErrorMsg != undefined) {
                    $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>');
                } else {
                    $.OKDialogAgency('<div class="tc">' + data + '</div>');
                }
                obj.parents(".op").attr("data-flag", "true");
                $("#createPreCustFollow").removeAttr("disabled");
                return false;
            }

            var message = "跟进添加成功！";
            $.dialog({
                id: "dialogAddPrecustFollow",
                content: '<div class="tc"></div>' + message + '</div>',
                close: function () {
                    $("#searchFormPot").submit();
                }
            });
            setTimeout(function () {
                art.dialog.get('dialogAddPrecustFollow').close();
            }, 1000);
            /*
            if ($("#hiddenOffSwitch").val() == "1") {
                $.OKCancelDialogAgency('<center>是否继续拨打？</center>', '消息',
                function () {
                    $("#callMobilePre").removeAttr("disabled");
                    $("#gdIndexPreCustomerList tr[flag=1]").remove();
                    clearPreWebSocketId();
                },
                function () { $("#searchFormPot").submit(); $("#hiddenAutoCall").val("1"); },
                null, '是', '否');
            }
            */
        })
    }
    else {
        reqData.FollowType = followType;
        reqData.CustKeyId = customerKeyId;
        $.AjaxAgency("/customer/precust-page-follow", reqData, function (data) {
            if (data) {
                $.dialog({
                    id: "dialogPreCustFollow",
                    title: "跟进内容",
                    width: 700,
                    lock: true,
                    content: data
                });
                $("#PreCustName").val(currentElement.attr("custName"));
                //var selectPhones = currentElement.attr("custPhone").split(',');
                var selectPhones = currentElement.parent().parent().find("td.phone").text().trim().split(',');
                var offSwitch = $("#hiddenOffSwitch").val();
                if (offSwitch == 1) {
                    var b = new Base64();
                    var rel = (b.decode(currentElement.parent().parent().find("span.sprealnum").text())).split(',');
                    for (var i = 0; i < selectPhones.length; i++) {
                        $("#PreCustTel").append("<option value='" + b.encode(rel[i]) + "'>" + selectPhones[i] + "</option>");
                    }
                }
                else {
                    for (var i = 0; i < selectPhones.length; i++) {
                        $("#PreCustTel").append("<option value='" + selectPhones[i] + "'>" + selectPhones[i] + "</option>");
                    }
                }
                $.inputStatistics2($("div .aui_content #txtContent"));
                agencyVerify.notNullInput("#createPreCustFollowForm", "#createPreCustFollowForm input[isnull=isNull]:visible", true, "blur");
                agencyVerify.nonnegativeIntInput("input[isint=1]", true);
                agencyVerify.bigOrSmallCompareAlert("#createPreCustFollowForm", "#RentPriceFrom:visible", "#RentPriceTo:visible", "最高价格不能低于最低价格", true);
                agencyVerify.bigOrSmallCompareAlert("#createPreCustFollowForm", "#BuyPriceFrom:visible", "#BuyPriceTo:visible", "最高价格不能低于最低价格", true);
                agencyVerify.notdefaultSelect("#createPreCustFollowForm", "#BuyReasonKeyId:visible", -1, "必须选择购房原因！", true);
                agencyVerify.notCheckedRadio("#createPreCustFollowForm", '#GenderKeyId input[type=radio]', "请选择客户性别");
                agencyVerify.notCheckedRadio("#createPreCustFollowForm", '#consignInfo input[type=radio]', "请选择客户意向");
                obj.parents(".op").attr("data-flag", "true");
            }
        });
    }
});

washSearch.FormBegin = function () {
    if ($(".wrong:not([type=sameCheckAjax])").length == 0) {
        $("#createPreCustFollow").attr("disabled", "disabled");
    }
};

washSearch.FormSuccess = function (data) {
    if (!data.Flag) {
        $.OKDialogAgency('<div class="tc">' + data + '</div>');
        $("#createPreCustFollow").removeAttr("disabled");
        return false;
    }

    var message = "跟进添加成功！";
    if (data.ErrorMsg) {
        message += data.ErrorMsg;
    }

    if (data.ErrorMsg == "接口回写异常，请刷新后再试") {
        message = "接口回写异常，请刷新后再试";
    }

    $.dialog({
        id: "dialogAddPrecustFollow",
        content: '<div class="tc"></div>' + message + '</div>',
        close: function () {
            window.location.reload();
        }
    });
    setTimeout(function () {
        art.dialog.get('dialogAddPrecustFollow').close();
    }, 2000);
    art.dialog.get("dialogPreCustFollow").close();
    /*
    if ($("#hiddenOffSwitch").val() == "1") {
        $.OKCancelDialogAgency('<center>是否继续拨打？</center>', '消息',
        function () {
            $("#callMobilePre").removeAttr("disabled");
            $("#gdIndexPreCustomerList tr[flag=1]").remove();
            clearPreWebSocketId();
        },
        function () { $("#searchFormPot").submit(); $("#hiddenAutoCall").val("1"); },
        null, '是', '否');
    }
    else {
        //$.OKDialogAgency('<div class="tc">跟进添加成功！</div>');
        //$("#searchFormPot").submit();
    }
    */
};

//清除websocketId
function clearPreWebSocketId() {
    $.AjaxAgency("/customer/clear-static-websocketid", { 'KeyId': $("#incommingPre").html() }, function () { });
}

//用来控制单选按钮，潜在客源和公客池是否可用
washSearch.RadioButtonAvailable = function () {
    var idFlag = $("#PotentialSpan input:checked").attr("id");
    if (idFlag == "potentialCustRadio") {
        if ($("#PreCustCount").val() == "0") {
            $("#publicCustRadio").removeAttr("disabled");
            $("#btnSubmitImport").removeAttr("disabled");
            $("#SystemCustomers").removeAttr("disabled");
        }
        if ($("#PreCustCount").val() == "1") {
            $("#publicCustRadio").attr("disabled", "disabled");
            $("#btnSubmitImport").attr("disabled", "disabled");
            $("#SystemCustomers").attr("disabled", "disabled");
        }
    }
    if (idFlag == "publicCustRadio") {
        if ($("#PubCustCount").val() == "0") {
            $("#potentialCustRadio").removeAttr("disabled");
            $("#btnSubmitImport").removeAttr("disabled");
            $("#SystemCustomers").removeAttr("disabled");
        }
        if ($("#PubCustCount").val() == "1") {
            $("#potentialCustRadio").attr("disabled", "disabled");
            $("#btnSubmitImport").attr("disabled", "disabled");
            $("#SystemCustomers").attr("disabled", "disabled");
        }
    }
    if (idFlag == "SystemCustomers") {
        if ($("#PreSystemCustomersCount").val() == "0") {
            $("#publicCustRadio").removeAttr("disabled");
            $("#potentialCustRadio").removeAttr("disabled");
            $("#btnSubmitImport").removeAttr("disabled");
        }
        if ($("#PreSystemCustomersCount").val() == "1") {
            $("#publicCustRadio").attr("disabled", "disabled");
            $("#potentialCustRadio").attr("disabled", "disabled");
            $("#btnSubmitImport").attr("disabled", "disabled");
        }
    }
    //alert("调用此方法判断复选框是否可用");

}

//第二次需求
var createSocketPre = function (custKeyId, phone) {
    $.AjaxAgency("/customer/create-webSocket", null, function (data) { startup(custKeyId, phone); });
}

//第二次需求，手动拨号打电话方法
function MakingCall(e) {
    if ($(e).attr("data-flag") == "true") {
        OverallObj = e;
    }
    //是否是公司资源池
    var isSysCus = $(e).attr("data-issyscus");
    var callType = 1;
    if (isSysCus == "true") {
        callType = 3
    }
    var offSwitch = $("#hiddenOffSwitch").val();
    if (offSwitch == "1") {
        if ($(e).attr("isMulti") == "1") {
            $.dialog({
                id: "phoneInfo",
                title: "拨打电话",
                init: function () { },
                lock: true,
                content: $("#phoneTable").html(),
            });
            var phones = $(e).parent().parent().find("td.phone").text();
            var b = new Base64();
            var rel = (b.decode($(e).parent().find("span.sprealnum").text())).split(',');
            var array = phones.split(',');
            for (var i = 0; i < array.length; i++) {
                $(".aui_dialog #InfoTable").append('<tr><td>' + array[i] + '</td><td><span class="sprealnum" style="display: none">' + b.encode(rel[i]) + '</span><a class="icon-phone" data-issyscus="' + isSysCus + '" aanoeffect="true" custkeyid="' + $(e).attr("custkeyid") + '" isMulti="0" onclick="MakingCall(this)" ></a></td></tr>');
            }
        }
        else {
            var custKeyId = $(e).attr("custkeyid");
            var phone = $(e).parent().find("span.sprealnum").text();
            //createSocketPre(custKeyId, phone);
            invokeProviderInterface(custKeyId, phone, callType);
        }
    }
}

//第二次需求
var startup = function (custKeyId, phone) {
    var inc = document.getElementById('incommingPre');
    var wsImpl = window.WebSocket || window.MozWebSocket;
    window.ws = new wsImpl($("#webSocketURL").val());

    ws.onmessage = function (evt) {
        if (!evt.data.match("^\{(.+:.+,*){1,}\}$")) {
            //alert("普通字符串");//服务器返回的SocketId
            inc.innerHTML = evt.data.toString();

            //准备就绪开始请求供应商接口
            invokeProviderInterface(custKeyId, phone);
        }
        else {

            //供应商调用webAPI返回的结果JSON格式
            var ret = jQuery.parseJSON(evt.data);
            if (ret.EmployeeCallState == "未接通") {
                $.OKDialogAgency('<div class="tc">拨打业务员电话失败！</div>');
                return false;
            }
            var custKeyid = ret.CustomerKeyId;
            var phoneInfos = ret.PhoneInfos;
            if (phoneInfos.length > 0) {
                for (var i = 0; i < phoneInfos.length; i++) {
                    //$.OKDialogAgency('<div class="tc">电话：' + phoneInfos[i].Phone + '    接通状态：' + phoneInfos[i].CallState + '</div>');
                    $(".aui_state_highlight").click();//关闭呼叫中请稍等对话框
                }
            }
            else {
                //phoneinfos数组中没电话信息
            }
        }
    };
    ws.onopen = function () {
        ws.send("");
    };
    ws.onclose = function () { }
}

//第二次需求，调用供应商打电话接口
var invokeProviderInterface = function(custKeyId, phone, callType) {
    /*var socketId = $("#incommingPre").html();
    if (socketId == "" || socketId == undefined) {
        $.OKDialogAgency('<div class="tc">WebSocket连接失败！</div>');
        return false;
    }*/
    var tempCallType = 1;
    if (callType == 3) {
        tempCallType = 3;
    }
    var reqData = {
        //'SocketId': socketId,
        'Phone': phone,
        'CustomerKeyId': custKeyId,
        'CityCode': 'ZY00022',
        'CallType': tempCallType
    };

    $.AjaxAgency("/customer/invokeProvider", reqData, function(data) {
        if (data.ErrorMsg != "" && data.ErrorMsg != undefined) {
            $.OKDialogAgency('<div class="tc">' + data.ErrorMsg + '</div>', true, function() {
                try {
                    var obj = OverallObj;
                    if (obj != null && obj != undefined) {
                        $(OverallObj).parent().parent().children(".op").children("a").css("color", "").removeClass("setcolor").attr("mobile", phone);
                    }
                    OverallObj = null;
                } catch(e) {

                }
            });
        } else {
            $.OKDialogAgency('<div class="tc">拨号中，请稍等......</div>', true, function() {
                try {
                    var obj = OverallObj;
                    if (obj != null && obj != undefined) {
                        $(OverallObj).parent().parent().children(".op").children("a").css("color", "").removeClass("setcolor").attr("mobile", phone);
                    }
                    OverallObj = null;
                } catch(e) {

                }
            });
        }
    });
};

